package com.ease.concurrent.threadpool.mrbird;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: chenhs
 * @date: Created in 6:29 2020/3/15
 * <p>
 * 1）shutdown与shutdownNow的区别：平滑关闭、暴力关闭！
 * 在执行shutdownNow方法后，线程池马上就被关闭了，正在执行中的两个任务被打断，并且返回了线程队列中等待被执行的两个任务。
 * 还可以看到shutdown和shutdownNow方法都不是阻塞的。
 * <p>
 * 2)常与shutdown搭配的方法有 awaitTermination()
 * <p>
 * 3)AbortPolicy策略：丢弃任务，并抛出RejectedExecutionException异常。
 **/
public class ShutdownTest {

    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS
                , new ArrayBlockingQueue<>(2), Thread::new, new ThreadPoolExecutor.AbortPolicy());

        threadPoolExecutor.execute(new shortTask());
        threadPoolExecutor.execute(new longTask());
        threadPoolExecutor.execute(new longTask());
        threadPoolExecutor.execute(new shortTask());

        //threadPoolExecutor.shutdown();
        //System.out.println("已经执行了线程池shutdown方法");

        //马上关闭，并返回还未被执行的任务
        //List<Runnable> runnables = threadPoolExecutor.shutdownNow();
        //System.out.println(runnables);
        //System.out.println("已经执行了线程池shutdownNow方法");

        //当等待超过设定时间时，会监测ExecutorService是否已经关闭，若关闭则返回true，否则返回false。该方法是阻塞的
        threadPoolExecutor.shutdown();
        boolean isShutdown = threadPoolExecutor.awaitTermination(3, TimeUnit.SECONDS);
        if (isShutdown) {
            System.out.println("线程池在3秒内成功关闭");
        } else {
            System.out.println("等了3秒还没关闭，不等了╰（‵□′）╯");
        }
        System.out.println("------------");
    }


    static class shortTask implements Runnable {
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(Thread.currentThread().getName() + "执行shortTask完毕");
            } catch (InterruptedException e) {
                System.err.println("shortTask执行过程中被打断" + e.getMessage());
            }
        }
    }

    static class longTask implements Runnable {
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(5);
                System.out.println(Thread.currentThread().getName() + "执行longTask完毕");
            } catch (InterruptedException e) {
                System.err.println("longTask执行过程中被打断" + e.getMessage());
            }
        }
    }

}
